package com.reason.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.security.KeyPair;


@Configuration//标记为配置类
@EnableAuthorizationServer//标记为授权服务
class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    /**
     * 数据源，用于从数据库获取数据进行认证操作，测试可以从内存中获取
     */
    @Autowired
    private DataSource dataSource;

    /**
     * jwt令牌转换器
     */
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;


    /**
     * SpringSecurity 用户自定义授权认证类
     */
    @Autowired
    UserDetailsService userDetailsService;

    /**
     *  授权认证管理器
     */
    @Autowired
    AuthenticationManager authenticationManager;

    /**
     * 令牌持久化存储接口
     */
    @Autowired
    TokenStore tokenStore;


    @Autowired
    private CustomUserAuthenticationConverter customUserAuthenticationConverter;

    /***
     * 用来配置客户端详情服务信息配置
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //从数据库oauth_client_details表中查询clientID的sceret密钥的查询
        clients.jdbc(dataSource).clients(clientDetails());
    }

    /***
     * 用来配置令牌（token）访问端点和令牌服务（token-service）
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //定义令牌的生成方式，这里为jwt生成方式
                .accessTokenConverter(jwtAccessTokenConverter)
                //认证管理器 密码模式的配置
                .authenticationManager(authenticationManager)
                //令牌存储
                .tokenStore(tokenStore)
                //用户信息service
                .userDetailsService(userDetailsService);
    }

    /***
     * 用来配置令牌端点的安全约束
     * @param oauthServer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                //允许表单认证
                .allowFormAuthenticationForClients()
                //BCryptPassword加密
                .passwordEncoder(new BCryptPasswordEncoder())
                //提供公钥密钥端点
                .tokenKeyAccess("permitAll()")
                //检测token
                .checkTokenAccess("isAuthenticated()");
    }


    /**
     * 交给容器管理，主要获取配置文件的证书信息
     */
    @Bean("keyProp")
    public KeyProperties keyProperties(){
        return new KeyProperties();
    }

    /**
     * 注入KeyProperties
     */
    @Resource(name = "keyProp")
    private KeyProperties keyProperties;

    /**
     * 客户端配置
     * @return
     */
    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }


    @Bean
    @Autowired
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    /****
     * JWT令牌转换器
     * @param customUserAuthenticationConverter
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(CustomUserAuthenticationConverter customUserAuthenticationConverter) {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyPair keyPair = new KeyStoreKeyFactory(
                //证书路径 changgou.jks
                keyProperties.getKeyStore().getLocation(),
                //证书秘钥 changgouapp
                keyProperties.getKeyStore().getSecret().toCharArray())
                .getKeyPair(
                //证书别名 changgou
                keyProperties.getKeyStore().getAlias(),
                //证书密码 changgou
                keyProperties.getKeyStore().getPassword().toCharArray());
        converter.setKeyPair(keyPair);
        //配置自定义的CustomUserAuthenticationConverter
        DefaultAccessTokenConverter accessTokenConverter = (DefaultAccessTokenConverter) converter.getAccessTokenConverter();
        accessTokenConverter.setUserTokenConverter(customUserAuthenticationConverter);
        return converter;
    }
}

